package com.superpai.view.db;

import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import com.superpai.common.Constants;
import com.superpai.domain.ShopCategory;

/**
 * @author Devin.Hu
 * @date 2011-8-24
 * @version V1.0
 * @description 商品分类数据库辅助类
 */
public class CategoryDBHelper extends BaseDBHelper {

	public CategoryDBHelper(Context context) {
		super(context, Constants.DBNAME, null, Constants.VERSION);
	}

	public CategoryDBHelper(Context context, String name, CursorFactory factory, int version) {
		super(context, name, factory, version);
	}

	/**
	 * 保存商品分类数
	 * 
	 * @param p
	 */
	public void saveItem(ShopCategory p) {
		SQLiteDatabase db = getWritableDatabase();
		db.execSQL("insert into category (cid , cname , sequence) values (?, ? , ?)", new Object[] { p.getCategoryId(), p.getDesc(), p.getSequence() });
		db.close();
	}

	/**
	 * 根据id查询商品分类数信息
	 * 
	 * @param id
	 * @return
	 */
	public ShopCategory findItemByPcode(String cid) {
		ShopCategory item = new ShopCategory();
		SQLiteDatabase db = getReadableDatabase();
		Cursor cs = db.rawQuery("select * from category where cid = ? ", new String[] { cid });
		if (cs.moveToFirst()) {
			item.setCategoryId(cs.getString(cs.getColumnIndex("cid")));
			item.setDesc(cs.getString(cs.getColumnIndex("cname")));
			item.setSequence(cs.getInt(cs.getColumnIndex("sequence")));
		}
		cs.close();
		db.close();
		return item;
	}

	/**
	 * 查询商品分类数列表信息
	 * 
	 * @param id
	 * @return
	 */
	public List<ShopCategory> findItemList() {
		ShopCategory item = null;
		List<ShopCategory> mList = new ArrayList<ShopCategory>();
		SQLiteDatabase db = getReadableDatabase();
		Cursor cs = db.rawQuery("select * from category", null);

		while (cs.moveToFirst()) {
			item = new ShopCategory();
			item.setCategoryId(cs.getString(cs.getColumnIndex("cid")));
			item.setDesc(cs.getString(cs.getColumnIndex("cname")));
			mList.add(item);
		}
		cs.close();
		db.close();
		return mList;
	}
	
	/**
	 * 查询商品分类数列表信息
	 * 
	 * @param id
	 * @return
	 */
	public void delList() {
		SQLiteDatabase db = getWritableDatabase();
		db.delete("category", null, null);
		db.close();
	}
}
